import { ref } from 'vue'
import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import { validateUser } from '../mock/users'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userInfo = ref({})

  function setToken(newToken) {
    token.value = newToken
    Cookies.set('token', newToken, { expires: 0.5 }) // 设置cookie，有效期12小时
  }

  function setUserInfo(info) {
    userInfo.value = info
  }

  function login(username, password) {
    return new Promise((resolve) => {
      const result = validateUser(username, password)
      if (result.success) {
        const token = `web-${username}-${Date.now()}`
        setToken(token)
        setUserInfo(result.userInfo)
      }
      resolve(result)
    })
  }

  function logout() {
    token.value = ''
    userInfo.value = {}
    Cookies.remove('token') // 删除cookie中的token
  }

  // 初始化时从cookie恢复token
  const savedToken = Cookies.get('token')
  if (savedToken) {
    token.value = savedToken
  }

  return { token, userInfo, login, logout }
})